package com.chouren.goandroid.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnPreDrawListener;

import com.chouren.goandroid.R;

public class TextArc extends View {
	private int number;
	private int tempNumber;
	private int depth;
	private float sweepAngle;
	private RectF rectF;
	private Paint paintEdge;
	private Paint paintInner;
	
	public TextArc(Context context, int number) {
		super(context);
		this.number = number;
		init();
	}

	private void init() {
		depth = (int) getResources().getDimension(R.dimen.number_depth);

		int blackColor = 0x70000000;
		paintEdge = new Paint();
		paintEdge.setAntiAlias(true); // 笔刷无抗锯齿功能
		paintEdge.setColor(blackColor); // 笔刷颜色
		paintEdge.setStrokeWidth(depth * 0.2f);// 笔刷粗细度
		paintEdge.setStyle(Style.STROKE);// 笔刷空心

		int whiteColor = 0xddffffff;
		paintInner = new Paint();
		paintInner.setAntiAlias(true);
		paintInner.setColor(whiteColor);
		paintInner.setTextSize(depth * 6.0f);
		paintInner.setStrokeWidth(depth * 0.2f);
		paintInner.setTextAlign(Align.CENTER);
		paintInner.setStyle(Style.STROKE);
		
		rectF = new RectF();
		rectF.set(depth * 0.5f, depth * 0.5f, depth * 18.5f, depth * 18.5f);
		setLayoutParams(new LayoutParams((int) (depth * 19.5f), (int) (depth * 19.5f)));
		
		getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
			@Override
			public boolean onPreDraw() {
				new Thread(new DrawTask()).start();
				getViewTreeObserver().removeOnPreDrawListener(this);
				return false;
			}
		});
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		
		canvas.drawArc(rectF, -270, 360, false, paintEdge);
		canvas.drawArc(rectF, -270, sweepAngle, false, paintInner);
		canvas.drawText(String.valueOf(tempNumber), depth * 9.7f, depth * 11.0f, paintInner);
	}
	
	class DrawTask implements Runnable {
		private int state;
		public void run() {
			while (true) {
				switch (state) {
				case 0:
					try {
						Thread.sleep(200);
						state = 1;
					} catch (InterruptedException e) {
					}
					break;
				case 1:
					try {
						Thread.sleep(50);
						sweepAngle += 3.6f;
						tempNumber++;
						postInvalidate();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					break;
				}
				if (tempNumber >= number) return;
			}
		}
	}

}
